﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using CAD2INTEX;
using CADInterface;
using INTEXTECH;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for SummaryForm.xaml
    /// </summary>
    /*
     * 1. 从CAD导入，
     * 2. 保存到XML
     * 3. 读取XML
     * 4. 产生intex的数据集
     * 5. 保存INTEX XML
     * 6. 读取Intex XML
     * 7. 导入数据
     * 
     * FieldDescription
FieldPopedom
FieldSearchCol
FormulaInfo
FuncInfo
FuncModuleInfo
LogInfo
MaxID
ReportData
ReportModule
RoleInfo
TableDescription
TechBeaming
TechDetail
TechMaster
ThreadCountInfo
WeavingMachineInfo
     */
    public partial class CAD2INTEX : DocumentBase
    {
        #region====================Properties=======================
        DataSet setCADMap = null;
        bool fail = false;
        string failreason = "";
        string root = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\");
        public OracleConnection OracleDB;
        public SqlConnection SqlServerDB;
        public OracleCommand orlReadCommand = new OracleCommand();
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public SETCAD2INTEX setUI;
        bool isrun = true;
        public DSTCADDB dbcad
        {
            get
            {
                return (DSTCADDB)TryFindResource("dbcad");
            }
        }
        public DSTCADDB SetJob
        {
            get
            {
                return (DSTCADDB)TryFindResource("SetJob");
            }
        }
        CollectionViewSource vwLogInfo
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwLogInfo");
            }
        }
        DataRow dwLogInfo
        {
            get
            {
                if (vwLogInfo.View == null)
                    return null;
                if ((DataRowView)vwLogInfo.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLogInfo.View.CurrentItem).Row;
            }
        }
        INTEXTECHData m_wintex;
        DSTCADDB setCAD2INTEX = new DSTCADDB();
        CAD2INTEXData m_Data, m_DataX;
        private DataRow dwUI; 
        ExcelX.ExcelLib.ExcelAgent m_exAgent;
        DataRow dwBSFARB, dwWASTAMM, dwBHSATZ;
        string UserID = "";
        string ART = "";
        DataRow dwBASTGA, dwBASTKE, dwWASTGA, dwWTGEW, dwWASTPASS, dwWASTKE;
        CollectionViewSource vwWDECK, vwVKPOS, vwBSSATZ, vwBHSATZ, vwBSFARB, vwWASTAMM, vwWASTKE,
            vwWTGEW, vwDRAFTING, vwWASTPASS, vwWTPASS, vwWABIND, vwWASTGA, vwBASTGA, vwUIABPOS, vwWPGAAUF, vwWFGAAUF;
        DataRow dwBSSATZ;
        DataTable tbGSDAT;
        DataTable tbWTSAER, tbWTSCHUSS, tbWABIND, tbWTEINZ, tbWTPASS, tbWADART;
        bool isWarpYarn = true;
        DataSet setDISPO = new DataSet();
        DataSet setUIABPOS = new DataSet();
        DataSet setVKPOS = new DataSet();
        DataSet setENV = new DataSet();
        DataSet setWEAVE = new DataSet();
        DataSet setUIWAART = new DataSet();
        DataTable tbDRAFTING = new DataTable();
        DataTable tbPEGPLAN = new DataTable();
        BackgroundWorker bgWorker;
        AB05ONData m_AB05;
        GreigeMasterData m_GM;
        DataTable tbUIABPOS, tbWFGAAUF, tbWPGAAUF, tbUIWAART;
        private string cadArt
        {
            get
            {
                return txtCADART.Text;
            }
        }
        private string FInterID
        {
            get
            {
                return txtFInterID.Text;
            }
        }
        private string FClothNO
        {
            get
            {
                return txtCADART.Text;
            }
        }
        private string FProductNO
        {
            get
            {
                string fproductno="";
                this.Dispatcher.Invoke(new Action(() =>
                {
                    fproductno=txtCADART.Text;
                }));   
                return fproductno;
            }
        }        
        private string FColorNO
        {
            get
            {
                return txtCADCOLOR.Text;
            }
        }

        public CAD2INTEX()
        {
            InitializeComponent();
            this.Name = "CAD2INTEX";
            this.Title = "CAD2INTEX"; 
        } 
        #endregion

        #region ===================Events========================
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                setUI = (SETCAD2INTEX)TryFindResource("setData");
                bgWorker = new BackgroundWorker();
                bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        } 
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                setUI = (SETCAD2INTEX)TryFindResource("setData");
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    SqlServerDB = (SqlConnection)dicParamater["SqlServerDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    m_Data = new CAD2INTEXData(OracleDB, proxy);
                    m_Data.SqlServerDB = SqlServerDB;
                    #region============TESTINGDATA================
                    txtFInterID.Text = "37532";
                    txtFInterID.Text = ReadLog();
                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"];
                    #endregion 
                    ReloadCon();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            AutoRun();
        }
        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID = m_Data.Left(txtUserID.Text.ToUpper() + "        ", 8);
            System.Security.SecureString SPassword = txtPassword.SecurePassword;
            txtLogIn.Background = new SolidColorBrush(Colors.Yellow);
            DataSet setResult = m_Data.LogIn(Mandant, userID, SPassword);
            if (setResult.Tables.Count > 0)
            {
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                UserID = userID;
                m_Data.UserID = userID;
                this.UserID = userID;

                m_Data.WorkingDate = DateTime.Now.Year.ToString() + m_Data.Right("00" + DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + DateTime.Now.Day.ToString(), 2);
                m_Data.MANDANT = Mandant;
                m_Data.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "已登录";
                txtLogIn.Background = new SolidColorBrush(Colors.Green);

            }
        }
        private void btnConvert2Intex_Click(object sender, RoutedEventArgs e)
        {
            fail = false;
            failreason = "";
            Convert2Intex(FInterID,ref fail, ref failreason);
        }

        private void btnUpload2Intex_Click(object sender, RoutedEventArgs e)
        {
            Upload2Intex();
        }
        private void btnDelete2Intex_Click(object sender, RoutedEventArgs e)
        {
            Delete2Intex();
        }
        private void btnResetSetDispo_Click(object sender, RoutedEventArgs e)
        {
            ResetSetDispo();
        }
        private void btnReloadCon_Click(object sender, RoutedEventArgs e)
        {
            ReloadCon();
        }
        private void dlgCADTechBeamingr_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        private void dlgTechDetail_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void txtCADCOLOR_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
        private void btnLogInfor_Click(object sender, RoutedEventArgs e)
        {
            LoadJob(FInterID, FProductNO);
        }
        private void btnAutoRun_Click(object sender, RoutedEventArgs e)
        {
            bgWorker.RunWorkerAsync();
        }
        private void txtCADART_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                if (FInterID == "")
                    return;

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnGetTechMaster_Click(object sender, RoutedEventArgs e)
        {
            LoadCAD(FInterID,FClothNO, FColorNO);
        }
        #endregion

        public void Convert2Intex(string fInterID, ref bool fail, ref string failreason)
        {
            DataSet setResult = new DataSet();
            try
            { 
                if (dbcad.TechMaster.Rows.Count == 0)
                    return;
                m_Data.SetCAD = dbcad;
                m_Data.SetCAD.Merge(setCADMap); 
                setResult = m_Data.ConvertToIntex(fInterID,ref fail,ref failreason);
                if (fail)
                {
                    return;
                }
                setCAD2INTEX.Clear();
                setCAD2INTEX.Merge(setResult);
                if (m_wintex == null)
                {
                    m_wintex = new INTEXTECHData(OracleDB, proxy);
                }
                m_wintex.ReSet(setCAD2INTEX, setDISPO);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public bool Upload2Intex()
        {
            bool result = true;
            try
            {
                if (m_wintex == null)
                {
                    m_wintex = new INTEXTECHData(OracleDB, proxy);
                }
                m_wintex.ReSet(setCAD2INTEX, setDISPO);
                result = m_wintex.Execute();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        }
        public void Delete2Intex()
        {
            if (m_wintex == null)
            {
                m_wintex = new INTEXTECHData(OracleDB, proxy);
            }
            m_wintex.ReSet(setCAD2INTEX, setDISPO);
            m_wintex.Delete();
        }
        public void ReloadCon()
        {
            DataSet setResult = new DataSet(); 
            setCADMap = new DataSet();
            setDISPO = m_Data.LoadSetDispo(txtSetDispo.Text.Trim());
            setCADMap.Merge(setDISPO);            
            string filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\CADMAPINTEX.XML");
            setResult.ReadXml(filePath);
            setCADMap.Merge(setResult);
            
            //setCADMap.Merge(setResult, false, MissingSchemaAction.Ignore);
            DataSet setTemp = new DataSet();
            filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\FINISHMAPINTEX.XML");
            setTemp.ReadXml(filePath);
            setCADMap.Merge(setTemp);
            setCADMap.Tables["FINISHMAP"].Clear();
            setResult = m_Data.QueryFINISHINGTECHMASTER();
            foreach (DataRow rf in setResult.Tables[0].Rows)
            {
                bool exist = false;
                var query = from DataRow rfc in setCADMap.Tables["FINISHMAP"].AsEnumerable()
                            where rfc["ITXFINISH"].ToString() == rf["FShortCode"].ToString()
                            select rfc;
                foreach (DataRow rq in query)
                {
                    exist = true;
                    rq["CADFINISH"] = rf["FFinishingTechName"];
                    rq["DESCRIPTION"] = rf["FFinishingTechName"];
                    rq["PROCESSFLOW"] = rf["FWholeFinishingName"];
                }
                if (!exist)
                {

                    DataRow rn = setCADMap.Tables["FINISHMAP"].NewRow();
                    rn["ROWID"]="x";
                    rn["ITXFINISH"] = rf["FShortCode"];
                    rn["CADFINISH"] = rf["FFinishingTechName"];
                    rn["DESCRIPTION"] = rf["FFinishingTechName"];
                    rn["PFID"]= rf["FShortCode"];
                    rn["PROCESSFLOW"] = rf["FWholeFinishingName"];
                    setCADMap.Tables["FINISHMAP"].Rows.Add(rn);
                    //rn["REMARK"] = rf["FWholeFinishingName"];
                }
            }
        }
        public void ResetSetDispo()
        {
            setDISPO = m_Data.ResetSetDispo(txtSetDispo.Text.Trim());
            setCADMap = new  DSTCADDB();
            DataSet setResult = new DataSet(); 
            string filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\CADMAPINTEX.XML");
            setResult.ReadXml(filePath);
            setCADMap.Merge(setResult);
            DataSet setTemp = new DataSet();
            filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\FINISHMAPINTEX.XML");
            setTemp.ReadXml(filePath);
            setCADMap.Merge(setTemp);
        }

        public void LoadJob(string fInterID, string FProductNO)
        {
            try
            {
                SetJob.Clear();
                DataSet setResult = m_Data.QueryLogInfor(fInterID, FProductNO);
                SetJob.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void AutoRun()
        {
            try
            {
                if (isrun == false)
                    return;
                foreach (DataRow dwLog in SetJob.LogInfo.Rows)
                {
                    if (isrun == false)
                        break;
                    AutoConvert(dwLog); 
                }
                if (isrun)
                {
                    SetJob.Clear();
                    LoadJob(ReadLog(), FProductNO);
                }
                if (SetJob.LogInfo.Rows.Count == 0)
                {
                    double miliseconds=1000 * 60 * 2;////5minutes    
                    System.Threading.Thread.Sleep(1000 * 60 * 2);
                    DateTime dat=DateTime.Now.AddMilliseconds(miliseconds);
                    EventDispatcher.Instance.RaiseStatus("下次转换开始时间是:" + dat.ToLongTimeString(), StatusEventType.StopProgress);
                }
                    AutoRun();                
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public void LoadCAD(string fInterID,string fClothNO, string fColorNo)
        {
            dbcad.Clear();
            DataSet setResult = new DataSet();
            try
            {
                string filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\CADDB\\CAD" + fInterID + ".XML");
                setResult = m_Data.QueryTechMaster(fClothNO, fColorNo);
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
                setResult.WriteXml(filePath);
                foreach (DataTable tbTemp in ReadFile(filePath).Tables)
                {
                    dbcad.Merge(tbTemp, false, MissingSchemaAction.Ignore);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public DataSet ReadFile(string filePath)
        {
            DataSet setResult = new DataSet();
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    setResult.ReadXml(filePath);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return setResult;
        }

        public void AutoConvert(DataRow dwLog)
        {

            DataSet setResult = new DataSet();            
            bool result = true;
            string fInterID = dwLog["FInterID"].ToString();
            string fClothNo = dwLog["FProductNO"].ToString();
            string fColorNO = dwLog["FClothNO"].ToString();
            EventDispatcher.Instance.RaiseStatus("正在转换:" + fInterID, StatusEventType.StartProgress);
            EventDispatcher.Instance.RaiseStatus("装载CAD数据:" + fClothNo + fColorNO, StatusEventType.StartProgress);
            LoadCAD(fInterID,fClothNo, fColorNO);
            fail = false;
            failreason = "";
            EventDispatcher.Instance.RaiseStatus("开始转换:" + fClothNo + fColorNO, StatusEventType.StartProgress);
            Convert2Intex(fInterID,ref fail,ref failreason);
            EventDispatcher.Instance.RaiseStatus("转换到Intex:" + fClothNo + fColorNO, StatusEventType.StartProgress);
            if (fail)
            {
                result = false;
            }
            else
            {
                result = Upload2Intex();
                EventDispatcher.Instance.RaiseStatus("保存到Intex:" + fClothNo + fColorNO, StatusEventType.StopProgress);
            }
            WritePFLog(result, failreason,dwLog);
        }
        public void WritePFLog(bool pass, string reason,DataRow dwLog)
        {
            DataTable tbLog = SetJob.LogInfo.Clone();
            DataSet setResult = new DataSet();
            DataSet setL = new DataSet();
            string logfile = "CADLOG";
            if (!pass)
            {
                logfile = "FAILLOG";
                tbLog.TableName = logfile;
            }
            else
            {
                logfile = "PASSLOG";
                tbLog.TableName = logfile;
            }

            if (System.IO.File.Exists(root + logfile + ".XML"))
            {
                setResult.ReadXml(root + logfile + ".XML");
                tbLog = setResult.Tables[logfile];
            }
            tbLog.Rows.Add(tbLog.NewRow().ItemArray = dwLog.ItemArray);
            setL.Merge(tbLog);
            setL.WriteXml(root + logfile + ".XML");
            //Last ID                 
            setL = new DataSet();
            tbLog = SetJob.LogInfo.Clone();
            logfile = "CADLOG";
            tbLog.TableName = logfile;
            tbLog.Rows.Add(tbLog.NewRow().ItemArray = dwLog.ItemArray);
            setL.Merge(tbLog);
            setL.WriteXml(root + logfile + ".XML"); 
        }
        public string ReadLog()
        {
            string result = "180660";
            result = "999999";
            try
            {
                if (System.IO.File.Exists(root + "CADLOG.XML"))
                {
                    DataSet setResult = new DataSet();
                    setResult.ReadXml(root + "CADLOG.XML");
                    DataTable tbLog = setResult.Tables["CADLOG"];
                    result = tbLog.Rows[0]["FInterID"].ToString();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        }
        private void dlgCADLogInfo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DataRowView drv = null;
            ItemsControl sd;
            ICollectionView view;
            try
            {
                sd = sender as ItemsControl;
                view = CollectionViewSource.GetDefaultView(sd.ItemsSource);
                if (e.AddedItems.Count > 0)
                {
                    drv = e.AddedItems[0] as DataRowView;
                    txtFInterID.Text = dwLogInfo["FInterID"].ToString();
                    txtCADART.Text = dwLogInfo["FProductNO"].ToString();
                    txtCADCOLOR.Text = dwLogInfo["FClothNO"].ToString();
                 
                    using (new LongOperation(this, "正在进行转换"))
                    {
                        AutoConvert(dwLogInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnStopRun_Click(object sender, RoutedEventArgs e)
        {
            IsRun.Text = "N";
        }

        private void IsRun_TextChanged(object sender, TextChangedEventArgs e)
        { 
                isrun = false;
                if (IsRun.Text.ToString() == "Y")
                    isrun = true; 
        }
    }
} 